﻿//Write a program that finds the index of given element in a sorted array of
//integers by using the binary search algorithm (find it in Wikipedia).


using System;
using System.Collections.Generic;

public class IndexOfGivenElement
{
    public static void Main()
    {
        Console.Write("Enter length of array L = ");
        int length = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter {0} integer numbers", length);
        int[] numbers = new int[length];
        for (int i = 0; i < length; i++)
        {
            numbers[i] = int.Parse(Console.ReadLine());
        }
        Sort(numbers);
        Console.WriteLine("Enter integer from array to find it position");
        int num = int.Parse(Console.ReadLine());
        int count = numbers.Length - 1;
        List<int> position = new List<int>();
        for (int i = 0; i < count; i++)
        {
            if (num == numbers[(count + i) / 2])
            {
                position.Add((count + i) / 2);
                
            }
            else if (num < numbers[(count + i) / 2])
            {
                count = (count + i) / 2;
            }
            else
            {
                i = ((count + i) / 2) - 1 ;
            }
        }
        if (position.Count == 0)
        {
            Console.WriteLine("The number you enter is not in the array");
        }
        else
        {
            Console.WriteLine("Position is {0}", position[0]);
        }
    }

    private static void Sort(int[] array)
    {
        for (int elemenIndex = 0; elemenIndex < array.Length; elemenIndex++)
        {
            int smallArrayElement = int.MaxValue;
            int tempVariable;
            int smallElementIndex = 0;
            for (int i = elemenIndex; i < array.Length; i++)
            {
                if (array[i] < smallArrayElement)
                {
                    smallArrayElement = array[i];
                    smallElementIndex = i;
                }
            }

            tempVariable = array[elemenIndex];
            array[elemenIndex] = smallArrayElement;
            array[smallElementIndex] = tempVariable;            
        }
    }
}